package com.bwt.top.bwt_ad_flutter.ad;

import android.app.Activity;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;

import com.bwt.top.ad.bean.AdInfo;
import com.bwt.top.ad.impl.BannerAd;
import com.bwt.top.ad.listener.BannerAdListener;
import com.bwt.top.ad.utils.AdUtil;
import com.bwt.top.bwt_ad_flutter.AdErrorUtil;
import com.bwt.top.bwt_ad_flutter.R;
import com.bwt.top.bwt_ad_flutter.config.BwtAdEventConfig;
import com.bwt.top.bwt_ad_flutter.manager.BwtAdManager;
import com.bwt.top.bwt_ad_flutter.model.AdParams;
import com.bwt.top.bwt_ad_flutter.util.LogUtil;
import com.bwt.top.exception.AdError;

public class BwtBannerAd extends BannerAdListener {

    @NonNull
    private final AdParams adParams;

    private BannerAd bannerAd;

    private FrameLayout adContainer;

    public BwtBannerAd(@NonNull AdParams adParams, @NonNull Activity activity){
        this.adParams = adParams;

        adContainer = new FrameLayout(activity);

        this.bannerAd = new BannerAd(activity,adContainer);

    }
    public void loadAd(){
        bannerAd.setAdId(adParams.getPosId());
        bannerAd.showCloseView();
        bannerAd.setAutoRefreshInterval(30);
        bannerAd.setAdListener(this);
        bannerAd.loadAd();
    }

    @NonNull
    public AdParams getAdParams() {
        return adParams;
    }

    @Override
    public void onAdReceive(AdInfo adInfo) {
        Log.d("bannerAd","开始加载广告--"+adInfo);
        BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_LOAD, adParams);
    }

    @Override
    public void onAdExpose(AdInfo adInfo) {
        LogUtil.log("广告被展示，adId: " + adParams.getAdId());
        BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_EXPOSE, adParams);
    }

    @Override
    public void onAdClick(AdInfo adInfo) {
        LogUtil.log("广告被点击，adId: " + adParams.getAdId());
        BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_CLICK, adParams);
    }

    @Override
    public void onAdClose(AdInfo adInfo) {
        LogUtil.log("广告被关闭，adId: " + adParams.getAdId());
        BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_CLOSE, adParams);
        release();
    }

    @Override
    public void onAdFailed(AdError adError) {
        LogUtil.log("广告获取失败，adId: " + adParams.getAdId() + ", error: " + AdErrorUtil.getError(adError));
        BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_FAILED, adParams, AdErrorUtil.getError(adError));
    }

    public FrameLayout getAdContainer() {
        return adContainer;
    }

    public void setAdContainer(FrameLayout adContainer) {
        this.adContainer = adContainer;
    }

    /**
     * 释放广告
     */
    public void release() {
        if (bannerAd != null) {
            bannerAd.release();
            bannerAd = null;
        }
    }
}
